package services

import (
	"fmt"
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/core/logs"
)

// SyncMeituanGroupOrders 同步美团团购订单
func SyncMeituanGroupOrders(storeId int64, meituanGroupId int64) (int, error) {
	// 获取美团服务实例
	meituanService, err := GetMeituanServiceByStoreId(storeId)
	if err != nil {
		logs.Error("获取美团服务失败: %v", err)
		return 0, err
	}

	// 获取团购活动信息
	var groupActivity *models.MeituanGroup
	if meituanGroupId > 0 {
		groupActivity, err = models.GetMeituanGroupById(meituanGroupId)
		if err != nil {
			logs.Error("获取团购活动失败: %v", err)
			return 0, fmt.Errorf("团购活动不存在")
		}
	}

	// 设置查询时间范围（最近24小时的订单）
	endTime := time.Now()
	startTime := endTime.Add(-24 * time.Hour)

	// 调用美团API获取订单列表
	logs.Info("开始从美团API获取团购订单，时间范围: %s - %s", 
		startTime.Format("2006-01-02 15:04:05"), 
		endTime.Format("2006-01-02 15:04:05"))
	
	orders, err := meituanService.GetOrders(startTime, endTime, "group")
	if err != nil {
		logs.Error("从美团API获取团购订单失败: %v", err)
		return 0, fmt.Errorf("从美团API获取订单失败: %v", err)
	}

	logs.Info("成功从美团API获取到 %d 条订单记录", len(orders))
	return processOrders(storeId, meituanGroupId, groupActivity, orders)
}

// processOrders 处理订单数据
func processOrders(storeId int64, meituanGroupId int64, groupActivity *models.MeituanGroup, orders []map[string]interface{}) (int, error) {
	count := 0
	
	// 获取美团配置
	meituanConfig, _ := models.GetMeituanByStoreId(storeId)
	if meituanConfig == nil {
		return 0, fmt.Errorf("美团配置不存在")
	}

	for _, orderData := range orders {
		if err := processSingleOrder(storeId, meituanGroupId, meituanConfig.Id, groupActivity, orderData); err != nil {
			logs.Error("处理订单失败: %v", err)
			continue
		}
		count++
	}

	logs.Info("美团团购订单同步完成，新增订单数: %d", count)
	return count, nil
}

// processSingleOrder 处理单个订单
func processSingleOrder(storeId int64, meituanGroupId int64, meituanConfigId int64, groupActivity *models.MeituanGroup, orderData map[string]interface{}) error {
	orderId, ok := orderData["order_id"].(string)
	if !ok || orderId == "" {
		return fmt.Errorf("订单数据缺少order_id字段")
	}

	// 检查是否团购订单类型
	orderType, _ := orderData["order_type"].(string)
	if orderType != "group" && orderType != "groupbuy" {
		return fmt.Errorf("跳过非团购订单: %s, 类型: %s", orderId, orderType)
	}

	// 如果指定了团购活动ID，检查订单是否属于该活动
	if meituanGroupId > 0 {
		dealId, _ := orderData["deal_id"].(string)
		if groupActivity != nil && dealId != groupActivity.MeituanGroupId {
			return fmt.Errorf("跳过非指定团购活动的订单: %s, 活动ID: %s", orderId, dealId)
		}
	}

	// 检查订单是否已存在
	existOrder, _ := models.GetMeituanGroupOrderByOrderId(orderId)
	if existOrder != nil {
		return updateExistingOrder(existOrder, orderData)
	}

	// 创建新订单
	return createNewOrder(storeId, meituanGroupId, meituanConfigId, orderData)
}

// updateExistingOrder 更新已存在的订单
func updateExistingOrder(existOrder *models.MeituanGroupOrder, orderData map[string]interface{}) error {
	newStatus, _ := orderData["status"].(string)
	if existOrder.Status != newStatus {
		existOrder.Status = newStatus
		if err := models.UpdateMeituanGroupOrder(existOrder); err != nil {
			logs.Error("更新美团团购订单状态失败: %v", err)
			return err
		}
		logs.Info("更新订单状态成功: %s, 新状态: %s", existOrder.OrderId, existOrder.Status)
	}
	return nil
}

// createNewOrder 创建新订单
func createNewOrder(storeId int64, meituanGroupId int64, meituanConfigId int64, orderData map[string]interface{}) error {
	order := parseOrderData(storeId, meituanGroupId, meituanConfigId, orderData)
	
	if _, err := models.AddMeituanGroupOrder(order); err != nil {
		logs.Error("保存美团团购订单失败: %v", err)
		return err
	}

	logs.Info("成功保存美团团购订单: %s", order.OrderId)
	return nil
}

// parseOrderData 解析订单数据
func parseOrderData(storeId int64, meituanGroupId int64, meituanConfigId int64, orderData map[string]interface{}) *models.MeituanGroupOrder {
	storeName, _ := orderData["store_name"].(string)
	if storeName == "" {
		storeName = "未知门店"
	}

	groupTitle := "美团团购商品"
	quantity := 1
	totalPrice := 0

	if items, ok := orderData["items"].([]interface{}); ok && len(items) > 0 {
		if item, ok := items[0].(map[string]interface{}); ok {
			if name, ok := item["name"].(string); ok && name != "" {
				groupTitle = name
			}
			if qty, ok := item["quantity"].(float64); ok {
				quantity = int(qty)
			}
			if price, ok := item["price"].(float64); ok {
				totalPrice = int(price * float64(quantity))
			}
		}
	}

	userName, _ := orderData["recipient_name"].(string)
	if userName == "" {
		userName = "匿名用户"
	}

	userPhone, _ := orderData["recipient_phone"].(string)
	
	var orderTime int64
	if timeStr, ok := orderData["create_time"].(string); ok && timeStr != "" {
		if t, err := time.Parse("2006-01-02 15:04:05", timeStr); err == nil {
			orderTime = t.Unix()
		} else {
			orderTime = time.Now().Unix()
		}
	} else {
		orderTime = time.Now().Unix()
	}

	voucherCode, _ := orderData["voucher_code"].(string)
	status, _ := orderData["status"].(string)

	return &models.MeituanGroupOrder{
		MeituanId:        meituanConfigId,
		MeituanGroupId:   meituanGroupId,
		StoreId:          storeId,
		StoreName:        storeName,
		OrderId:          orderData["order_id"].(string),
		OrderTime:        orderTime,
		GroupTitle:       groupTitle,
		UserName:         userName,
		UserPhone:        userPhone,
		Quantity:         quantity,
		TotalPrice:       totalPrice,
		Status:           status,
		ProcessStatus:    "pending",
		IsProcessed:      0,
		VoucherCode:      voucherCode,
		VoucherValidTime: time.Now().Add(30 * 24 * time.Hour).Unix(),
		IsUsed:           0,
	}
}
